/**
 * Created by lenovo on 2017/3/9.
 */
import Schema from 'async-validator'

/**
 * 通用step.fields校验，传入校验函数，当结果>0是认为校验未通过
 * */
function fieldsValid(value,callback,func,errorText){
  let errors = [],text=errorText||"error text";
  if (value && Array.isArray(value)) {
    let len = value.filter(func).length;
    if (len > 0)
      errors.push(new Error(text));
  }
  callback(errors);
}

function __CommonStepValid__(step, func,descriptor){
  let validator = new Schema(descriptor);
  return validator.validate(step, func)
}
/**
 * 校验规则：
 * descriptor:{
 *   '属性名称'：规则
 * }
 * 规则参考 https://github.com/yiminghe/async-validator
 * */
export default {
  TableOutput(step, func){
    let descriptor={
      connection: {type: "string", required: true, message: "请选择一个数据源"},
      fields(rule, value, callback){
        fieldsValid(value,callback,
          el => (el.stream_name==null||el.stream_name.trim() == "" )|| (el.column_name==null||el.column_name.trim() == ""),
          "流字段或者表字段不能为空，删除记录或者修改空的字段")
      }
    };
    return __CommonStepValid__(step, func,descriptor);
  },
  ReplaceString(step, func){
    let descriptor={
      fields(rule, value, callback){
        fieldsValid(value,callback,
          el => {
            let in_stream_name = el.in_stream_name || "", out_stream_name = el.out_stream_name || "";
            return in_stream_name.trim() == "" || out_stream_name.trim() == ""
          },
          "输入流字段或者输出字段不能为空，删除记录或者修改空的字段")
      }
    };
    return __CommonStepValid__(step, func,descriptor);
  },
  Calculator(step, func){
    let descriptor={
      fields(rule, value, callback){
        fieldsValid(value,callback,
          el => el.field_name.trim() == "" || el.field_name.trim() == "",
          "流字段不能为空，删除记录或者修改空的字段")
      }
    };
    return __CommonStepValid__(step, func,descriptor);
  },
  RowGenerator(step, func){
    let descriptor={
      fields(rule, value, callback){
        fieldsValid(value,callback,el => el.name.trim() == "","名称不能为空，删除记录或者修改空的字段")
      }
    };
    return __CommonStepValid__(step, func,descriptor);
  },
  GetVariable(step, func){
    let descriptor={
      fields(rule, value, callback){
        fieldsValid(value,callback,el => el.name.trim() == ""|| el.variable.trim() == "","名称或变量不能为空，删除记录或者修改空的字段")
      }
    };
    return __CommonStepValid__(step, func,descriptor);
  },
  SystemInfo(step, func){
    let descriptor={
      fields(rule, value, callback){
        fieldsValid(value,callback,el => el.name.trim() == ""|| el.type.trim() == "","名称或变量不能为空，删除记录或者修改空的字段")
      }
    };
    return __CommonStepValid__(step, func,descriptor);
  },
  Validator(step, func){
    let descriptor={
      send_false_to: {type: "string", required: true, message: "请选择一个错误处理步骤"},
    };
    return __CommonStepValid__(step, func,descriptor);
  }
};
